<template>
  <el-card>
    <el-form
      label-width="100px"
      :model="spuInfo"
      :rules="spuRules"
      ref="spuFormRef"
    >
      <el-form-item label="SPU名称" prop="spuName">
        <el-input autocomplete="off" v-model="spuInfo.spuName" />
      </el-form-item>
      <el-form-item label="品牌" prop="tmId">
        <el-select v-model="spuInfo.tmId" placeholder="请选择品牌">
          <el-option
            :label="trademark.tmName"
            v-for="trademark in trademarkList"
            :key="trademark.id"
            :value="trademark.id"
          />
          <!-- <el-option label="Zone two" value="beijing" /> -->
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述" prop="description">
        <el-input type="textarea" v-model="spuInfo.description"></el-input>
      </el-form-item>
      <el-form-item label="SPU图片" prop="spuImageList">
        <el-upload
          v-model:file-list="spuInfo.spuImageList"
          :action="`${BASE_URL}/admin/product/upload`"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>
        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性" prop="spuSaleAttrList">
        <el-select
          v-model="spuInfo.spuSaleAttr"
          :placeholder="`还有${filterBaseSaleAttrValueList.length}个未选择`"
        >
          <el-option
            :label="baseSaleAttr.name"
            :value="baseSaleAttr.name"
            v-for="baseSaleAttr in filterBaseSaleAttrValueList"
            :key="baseSaleAttr.id"
          />
        </el-select>
        <el-button
          style="margin-left: 10px"
          :icon="Plus"
          type="primary"
          @click="addSaleAttr"
          >添加销售属性</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-table :data="spuInfo.spuSaleAttrList" border style="width: 100%">
          <el-table-column
            label="序号"
            type="index"
            width="100px"
            align="center"
          ></el-table-column>
          <el-table-column prop="saleAttrName" label="属性名"></el-table-column>
          <el-table-column prop="spuSaleAttrValueList" label="属性值名称列表">
            <template v-slot="{ row, $index }">
              <el-tag
                v-for="tag in row.spuSaleAttrValueList"
                :key="tag"
                class="mx-1"
                closable
                :disable-transitions="false"
                @close="handleClose(row, tag)"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input
                v-if="row.inputVisible"
                ref="InputRef"
                v-model="inputValue"
                class="ml-1 w-20"
                size="small"
                @keyup.enter="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              />
              <el-button
                v-else
                class="button-new-tag ml-1"
                size="small"
                @click="showInput(row)"
                :icon="Plus"
              >
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作">
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="取消"
                icon-color="#626AEF"
                title="您确定要删除此条数据吗?"
                @confirm="deleteAttr($index)"
              >
                <template #reference>
                  <el-button
                    :icon="Delete"
                    type="danger"
                    size="small"
                  ></el-button>
                </template>
              </el-popconfirm>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitSpuForm(spuFormRef)"
          >保存</el-button
        >
        <el-button type="default" @click="emits('changeScene', 1)"
          >取消</el-button
        >
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "SpuForm",
};
</script>
<script lang="ts" setup >
import { onMounted, ref, reactive, computed, nextTick } from "vue";
import { Plus, Edit, Delete, InfoFilled } from "@element-plus/icons-vue";
import { ElMessage, ElInput } from "element-plus";
import {
  reqGetTrademarkAllList,
  reqGetBaseSaleAttrList,
  reqPostSpuInfo,
  reqGetSpuSaleAttrList,
  reqGetSpuImageList,
  updateSpuInfo,
} from "@/api/product/spu";
import type {
  UploadProps,
  UploadUserFile,
  FormInstance,
  FormRules,
} from "element-plus";
import { useCategoryListStore } from "@/stores/categoryList";
const categoryStore = useCategoryListStore();
const emits = defineEmits(["changeScene"]);
const props = defineProps(["currentSpuInfo"]);
console.log("props", props);

const trademarkList = ref([]);
const baseSaleAttrList = ref([]);
// 挂载后就需要所有品牌名称和售卖属性 多个一起发送用all，try，catch

onMounted(async () => {
  // 获取品牌数据和属性列表
    const { id } = spuInfo;
    let promises = [reqGetTrademarkAllList(), reqGetBaseSaleAttrList()];
    //
    if (id) {
      promises = promises.concat([
        reqGetSpuSaleAttrList(id),
        reqGetSpuImageList(id),
      ]);
    }
  try {
    const [
      responseTrademarkAllList,
      responseBaseSaleAttrList,
      responseSpuSaleAttrList,
      responseSpuImageList,
    ] = await Promise.all(promises);
    trademarkList.value = responseTrademarkAllList;
    baseSaleAttrList.value = responseBaseSaleAttrList;
    console.log(responseBaseSaleAttrList);
    // console.log(responseTrademarkAllList);
    console.log("spuImageList", responseSpuImageList);
    console.log("responseSpuSaleAttrList", responseSpuSaleAttrList);
    if (responseSpuImageList && responseSpuSaleAttrList) {
      spuInfo.spuImageList = responseSpuImageList.map(item => {
        return {
          ...item,
          name: item.imgName,
          url: item.imgUrl,
        };
      });
      spuInfo.spuSaleAttrList = responseSpuSaleAttrList;
    }
  } catch (error) {
    ElMessage.error("获取属性失败");
  }
});

// 图片部分
const fileList = ref<UploadUserFile[]>([
  // {
  //   name: "food.jpeg",
  //   url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
  // },
  // {
  //   name: "food.jpeg",
  //   url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
  // },
  // {
  //   name: "food.jpeg",
  //   url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
  // },
  // {
  //   name: "food.jpeg",
  //   url: "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
  // },
]);

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const BASE_URL = import.meta.env.VITE_API_URL;
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  spuInfo.spuImageList = uploadFiles;
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
// 上传成功之前
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  const imgType = ["image/jpeg", "images/jpg", "images/png"];
  // if (rawFile.type !== "image/jpeg") {
  if (!imgType.includes(rawFile.type)) {
    ElMessage.error("上传图片的格式只能是jpg/png/jpeg,请重新选择");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能超过2M,请重新选择...!");
    return false;
  }
  return true;
};
// 上传成功之后 收集图片数组
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile,
  uploadFiles
) => {
  // console.log(response, uploadFile, uploadFiles);
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  // spuInfo.spuImageList.push({
  //   imgName:uploadFile.name,
  //   imgUrl:response.data || uploadFile.url
  //   // name: uploadFile.name,
  //   // url: response.data || uploadFile.url,
  // });
  spuInfo.spuImageList = uploadFiles; //发送过去的是name,url
  // 清空图片校验
  spuFormRef.value!.clearValidate(["spuImageList"]);
  // trademark.logoUrl = response.data;
};

// 定义一个存储spu相关数据的变量,点击保存时传递的数据
const spuInfo = reactive({
  category3Id: 0,
  description: "",
  spuImageList: [],
  spuName: "",
  spuSaleAttrList: [], // 基本销售属性
  spuSaleAttr: "", //颜色，尺码
  tmId: "",
  ...props.currentSpuInfo
});
// 点击添加销售属性spuInfo.spuSaleAttr
// 选取了一项销售属性，如果没有添加具体的属性值，是不能继续选择销售属性的
const addSaleAttr = () => {
  if (
    spuInfo.spuSaleAttrList.length &&
    spuInfo.spuSaleAttrList.some(
      (item) => item.spuSaleAttrValueList.length === 0
    )
  )
    return ElMessage.error("属性值不能为空");
    const id = baseSaleAttrList.value.find(item=>item.name === spuInfo.spuSaleAttr).id 
  spuInfo.spuSaleAttrList.push({
    baseSaleAttrId:id,
    inputValue: false,
    saleAttrName: spuInfo.spuSaleAttr,
    spuSaleAttrValueList: [],
  });
  // 清空下拉框选项
  spuInfo.spuSaleAttr = "";
  // 校验成功后清空规则 这个可以不写，添加成功后，会自动清除掉
  // spuFormRef.value!.clearValidate(["spuSaleAttrList"]);
};

// 计算属性，添加销售属性时的移除效果
const filterBaseSaleAttrValueList = computed(() => {
  return baseSaleAttrList.value.filter((item) => {
    return !spuInfo.spuSaleAttrList.find(
      (obj) => item.name === obj.saleAttrName
    );
  });
});

// 添加销售属性的tag
const inputValue = ref("");
const spuSaleAttrValueList = ref([]);
const inputVisible = ref(false);
const InputRef = ref<InstanceType<typeof ElInput>>();

const handleClose = (row, tag: string) => {
  row.spuSaleAttrValueList.splice(row.spuSaleAttrValueList.indexOf(tag), 1);
};

const showInput = (row) => {
  row.inputVisible = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};

const handleInputConfirm = (row) => {
  if (inputValue.value) {
    const repeat = row.spuSaleAttrValueList.find(
      (item) => item.saleAttrValueName === inputValue.value
    );
    if (repeat) {
      ElMessage.error("属性值不能重复，请重新输入");
      row.inputVisible = false;
      inputValue.value = "";
      return;
    }
    const id = baseSaleAttrList.value.find(item=>item.name === row.saleAttrName).id
    row.spuSaleAttrValueList.push({
      baseSaleAttrId:row.baseSaleAttrId,
      isChecked: '0',
      saleAttrName: row.saleAttrName,
      saleAttrValueName: inputValue.value
    });
    console.log(inputValue.value,row.saleAttrName);
  }
  row.inputVisible = false;
  inputValue.value = "";
};

// 删除table中属性值
const deleteAttr =  (index: number) => {
  spuInfo.spuSaleAttrList.splice(index,1);
  ElMessage.success("删除属性值成功");
};
// 添加spu对应的校验规则
const formSize = ref("default");
const spuFormRef = ref<FormInstance>();
const spuRules = reactive<FormRules>({
  spuName: [
    { required: true, message: "请输入SPU名称", trigger: "blur" },
    { min: 1, max: 10, message: "SPU名称在1-10个字符之间", trigger: "blur" },
  ],
  tmId: [{ required: true, message: "请输入SPU品牌", trigger: "change" }],
  description: [{ required: true, message: "请输入SPU描述", trigger: "blur" }],
  spuImageList: [
    {
      required: true,
      message: "请至少选择一张图片",
      type: "array",
      trigger: "change",
    },
  ],
  spuSaleAttrList: [
    {
      required: true,
      message: "请至少添加一个属性",
      type: "array",
      trigger: "change",
    },
  ],
});
// 提交前的校验 发送请求时还要判断是添加还是更新
const submitSpuForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // 基础销售是不是有属性值，如果有一项无值 不能提交
      if (
        spuInfo.spuSaleAttrList.length &&
        spuInfo.spuSaleAttrList.some(
          item => item.spuSaleAttrValueList.length ===0
        )
      ) {
        ElMessage.error("属性值不能为空，请添加");
        return;
      }
      // 获取要提交的数据图片数组，3id，发送给服务器的是imgUrl，imgName
      spuInfo.category3Id = categoryStore.category3Id as number;
      spuInfo.spuImageList = spuInfo.spuImageList.map(item=>{
        return {
          imgName:item.name,
          imgUrl:item.response?.data || item.url
        }
      })
      // 发送添加请求或更新
      if (spuInfo.id) {
        await updateSpuInfo(spuInfo);
        ElMessage.success("属性更新成功！");
      } else {
        await reqPostSpuInfo(spuInfo);
        ElMessage.success("属性添加成功！");
      }
      emits("changeScene", 1);
      console.log("submit!");
    } else {
      console.log("error submit!", fields);
    }
  });
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.el-dialog {
  margin-top: 50px;
}
</style>